<!-- 图标列表按钮 -->
<template>
  <div class="iconListX" ref="fatherDom">
    <div class="iconItem xhAll" :class="{active: nowActive.id == item.id}"
         v-for="(item,index) in listD" :key="item.id"
         @click="clickFn(item)">
      <popover-x trigger="hover" effect="dark" :disabled="!item.help">
        <slot name="text" :row="item">
          <icon-x v-bind="item"/>
        </slot>

        <template #content>
          <div>
            {{ item.help }}
          </div>
        </template>
      </popover-x>
    </div>
    <div class="itemBgc"></div>
  </div>
</template>

<script setup>
import { onMounted,ref,nextTick,watch } from 'vue'
import IconX from './xhykIcon.vue'
import PopoverX from './xhykPopover.vue'

const props = defineProps({
  defaultValue: {
    type: Object,
    default: {id: 0}
  },

  list: {
    type: Object,
    default: [
      {type: 'setting', size: 16,help:''},
      {type: 'menu'},
      {type: 'plus'},
    ]
  },
})

const emit = defineEmits(['update:modelValue', 'change'])


// region 处理数据

// 每个item的宽度
const itemWidth = ref('0px')

const itemWidthNumber = ref(0)

const fatherDom = ref({})

const listD = ref([])
watch(() => props.list, (newV, oldV) => {
  listD.value = []
  if (newV.length > 0) {
    newV.forEach((row, index) => {
      row.id = index
      listD.value.push(row)
    })
  }
  nextTick(() => {
    const width = window.getComputedStyle(fatherDom.value).width
    const widthNumber = parseFloat(width)
    itemWidthNumber.value = widthNumber / newV.length
    itemWidth.value = `${widthNumber / newV.length}px`
  })
}, {immediate: true, deep: true})
// endregion


// region 点击事件

// 当前背景的左边距离
const leftValue = ref('0px')

// 当前活跃按钮
const nowActive = ref({})

const clickFn = (row) => {
  nowActive.value = row
  nextTick(() => {
    let indexNumber = listD.value.findIndex(row => row.id == nowActive.value.id) || 0
    if (indexNumber == -1) {
      indexNumber = 0
    }
    const style = window.getComputedStyle(fatherDom.value)
    var paddingLeft = style.getPropertyValue("padding-left");
    leftValue.value = `${indexNumber * itemWidthNumber.value + parseFloat(paddingLeft)}px`
  })
  emit('change', row)
}
// endregion


onMounted(() => {
  nowActive.value = props.defaultValue
  clickFn(props.defaultValue)
})


</script>

<style scoped lang='scss'>
.iconListX {
  display: inline-flex;
  align-items: center;
  background-color: #fff;
  padding: 0px 6px;
  height: 30px;
  cursor: pointer;
  position: relative;
  border-radius: 4px;
}

.iconItem {
  height: 100%;
  padding: 0px 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: transparent;
  z-index: 1;
  color: #495060;
}

.active {
  color: var(--menuFontColor);
  transition: all 0.35s ease 0s;
}

.itemBgc {
  background-color: var(--menuSysColor);
  width: v-bind(itemWidth);
  top: 2px;
  bottom: 2px;
  left: v-bind(leftValue);
  position: absolute;
  border-radius: 4px;
  transition: all 0.35s ease 0s;
}
</style>